#include <stdlib.h>
#include <string>
#include <iostream>
#include <memory>
#include <rise/common/exmacros.h>
#include <rise/common/Log.h>
#include <rise/common/Exception.h>
#include <rise/common/DataEncoder.h>
#include <rise/common/StreamBuffer.h>
#include <staff/common/Value.h>
#include <staff/common/QName.h>
#include <staff/common/Attribute.h>
#include <staff/common/DataObject.h>
#include <staff-mq/client/Publisher.h>
#include "ComplexData.h"
#include "ComplexDataProxy.h"


int main(int nArgs, char* szArgs[])
{
  std::string sServerHost = "127.0.0.1";
  unsigned short ushServerPort = 8768;

  for (int nArg = 1; nArg < nArgs; ++nArg)
  {
    if(szArgs[nArg])
    {
      const std::string& sArg = std::string(szArgs[nArg]);
      if (sArg.substr(0, 2) == "-s")
      {
        sServerHost = sArg.substr(2);
      }
      else
      if (sArg.substr(0, 2) == "-p")
      {
        ushServerPort = static_cast<unsigned short>(atoi(sArg.substr(2).c_str()));
      }
      else
      if (sArg.substr(0, 2) == "-h")
      {
        std::cerr << "Publisher multithreading test.\n\n"
            << szArgs[0] << "[ -h][ -s<Server host>][ -p<port>]\n\n";
        return 0;
      }
      else
      {
        std::cerr << "unknown arg: " << sArg << "\n";
        return 1;
      }
    }
  }


  try
  {
    smq::Publisher tPublisher;
    tPublisher.Init("publisher_test2clients", sServerHost, ushServerPort);

    tPublisher.CreateQueue("queue-complex");

    // first message type
    {
      staff::CDataObject tdoMsg("msg");
      
      ComplexStruct stComplex;
      
      // filling struct
      stComplex.sName = "complex struct";
      stComplex.lsStructs.push_back(MyStruct(1, 1.1, "text 1 1.0"));
      stComplex.lsStructs.push_back(MyStruct(4, 2.2, "text 2 2.2"));
      stComplex.lsStructs.push_back(MyStruct(4, 3.3, "text 3 3.3"));
      
      // serializing to data object
      tdoMsg << stComplex;

      // publishing into queue
      std::cout << "Publishing message into \"queue-complex\"" << std::endl;
      tPublisher.Publish("queue-complex", tdoMsg);
    }

    tPublisher.RemoveQueue("queue-complex");
  }
  RISE_CATCH_ALL

  return 0;
}
